package com.example.musicplayer.activity;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.example.musicplayer.R;
import com.example.musicplayer.adapter.TabsAdapter;
import com.example.musicplayer.entity.Music;
import com.example.musicplayer.fragment.FindFragment;
import com.example.musicplayer.fragment.HomeFragment;
import com.example.musicplayer.fragment.MineFragment;
import com.example.musicplayer.fragment.VideoFragment;
import com.example.musicplayer.service.MusicService;
import com.example.musicplayer.util.MusicNotification;
import com.example.musicplayer.util.MusicPopUpWindow;
import com.example.musicplayer.util.SingletonMediaPlayer;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.util.ArrayList;
import java.util.List;


/**
 * @author 张强
 * @date 2020/07/14
 * <p>
 * 主页
 */
public class HomeActivity extends AppCompatActivity implements View.OnClickListener {

    private ViewPager mViewPager;
    private BottomNavigationView mBottomNavigationView;
    private List<Fragment> fragments;
    private MenuItem menuItem;
    private ImageView mAlbumImg; // 专辑图片
    private TextView mMusicName; // 音乐名称
    private ImageView mStartOrPause;// 暂停和播放按钮
    private ImageView mMusicListButton; // 音乐列表按钮
    private MusicService.MusicBinder mMusicService; // 音乐服务
    private Music mCurrentMusic; // 当前正在播放的音乐
    private MusicPopUpWindow popWnd; // 底部歌单弹出栏

    // 动态刷新播放和暂停按钮的样式
    private Handler mHandler = new Handler();
    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (mMusicService.isPlaying()) {
                        mStartOrPause.setImageResource(R.drawable.stop_play_music_button);
                    } else {
                        mStartOrPause.setImageResource(R.drawable.start_play_music_button);
                    }
                }
            });
            mHandler.postDelayed(mRunnable, 16);
        }
    };
    private SingletonMediaPlayer mediaPlayer = SingletonMediaPlayer.getMediaPlayer();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i("--------------", "HomeActivity onCreate");
        setContentView(R.layout.activity_home);
        mMusicService = MusicService.getMusicService();
        initComponent(); // 初始化界面控件
        initFragment();  // 初始化Fragment
        setViews();      // 初始化控件样式
        TabsAdapter adapter = new TabsAdapter(getSupportFragmentManager(), fragments);
        mViewPager.setAdapter(adapter);



        // 底部导航栏选择改变时，切换到对应的viewpager
        mBottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.home_music:
                        mViewPager.setCurrentItem(0);
                        break;
                    case R.id.home_video:
                        mViewPager.setCurrentItem(1);
                        break;
                    case R.id.home_find:
                        mViewPager.setCurrentItem(2);
                        break;
                    case R.id.home_my:
                        mViewPager.setCurrentItem(3);
                        break;
                    default:
                        break;
                }
                return true;
            }
        });

        // viewpager切换到对应页面时，改变底部导航栏的选择项
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (menuItem == null) {
                    menuItem = mBottomNavigationView.getMenu().getItem(0);
                }
                menuItem.setChecked(false);  //设置为未选中
                menuItem = mBottomNavigationView.getMenu().getItem(position); //选中某个item
                menuItem.setChecked(true);   //设置为选中状态
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

        mHandler.postDelayed(mRunnable, 16);
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i("--------------", "onPause");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("----------------", "HomeActivity onDestroy");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.i("----------------", "onStop");
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 切换歌曲时改变歌曲名称和专辑名称
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                Log.i("=================", "omPrepared is running");
                setViews();
            }
        });
        Log.i("---------------", "onResume");
        setViews();
    }

    /**
     * 初始化Fragment
     */
    private void initFragment() {
        fragments = new ArrayList<>();
        fragments.add(new HomeFragment()); //初始化首页Fragment
        fragments.add(new VideoFragment()); //初始化视频Fragment
        fragments.add(new FindFragment());  //初始化动态Fragment
        fragments.add(new MineFragment());    //初始化我的Fragment
    }

    /**
     * 初始化界面控件
     */
    private void initComponent() {
        mViewPager = findViewById(R.id.viewpager);
        mBottomNavigationView = findViewById(R.id.bottom_navigation_view);
        mAlbumImg = findViewById(R.id.bottom_album_img);
        mMusicName = findViewById(R.id.bottom_music_name);
        mStartOrPause = findViewById(R.id.bottom_start_or_pause);
        mMusicListButton = findViewById(R.id.bottom_music_list);
        mStartOrPause.setOnClickListener(this);
        mMusicListButton.setOnClickListener(this);
    }

    // 设置界面控件样式
    private void setViews() {
        Log.i("===========", "更新首页底部播放栏");
        // 获取当前正在播放的音乐
        mCurrentMusic = mMusicService.getCurrentMusic();
        // 设置专辑图片
        mAlbumImg.setImageBitmap(mCurrentMusic.getAlbumArt());
        // 设置歌曲名称
        mMusicName.setText(mCurrentMusic.getName());
        // 设置歌曲名称选中
        mMusicName.setSelected(true);
    }


    public void goToMusicPlayPage(View view) {
        Intent intent = new Intent(this, PlayMusicActivity.class);
        startActivity(intent);
    }

    public void onBackPressed() {
        Intent intent = new Intent(Intent.ACTION_MAIN); //设置该intent的action为action main。相当于调用了setAction
        intent.addCategory(Intent.CATEGORY_HOME); //添加category
        startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bottom_start_or_pause:
                if (mMusicService.isPlaying()) { // 歌曲正在播放
                    sendNotificationBroadCast(MusicNotification.ACTION_START_OR_PAUSE); // 发送广播
                    mStartOrPause.setImageResource(R.drawable.stop_play_music_button);  // 设置按钮样式
                } else { // 歌曲暂时没有播放
                    sendNotificationBroadCast(MusicNotification.ACTION_START_OR_PAUSE); // 发送广播
                    mStartOrPause.setImageResource(R.drawable.start_play_music_button); // 设置按钮样式
                }
                break;
            case R.id.bottom_music_list:
                popWnd = new MusicPopUpWindow(this, mMusicService);
                popWnd.showAtLocation(v, Gravity.BOTTOM, 0, 0);
                break;
            default:
                break;
        }
    }

    /**
     * 发送广播
     *
     * @param action 指定Intent的action参数
     */
    private void sendNotificationBroadCast(String action) {
        Intent intent = new Intent();
        intent.setAction(action);
        sendBroadcast(intent);
    }
}